// pages/cart/cart.js
let app = getApp();
import Dialog from '../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    cartActive: 0,
    good_kd: [],//快递 所有数据
    good_group: [],//到店 所有数据
    picArr_kd: [],//标签
    picArr_group: [],//标签
    checkBoxGoodsGroup: [],//到店 选中列表
    checkBoxGoodsKd: [],//快递 选中列表
    isCheckAllGroup: true,
    isCheckAllKd: true,
    groupTotalPrice: 0,//总价
    kdTotalPrice: 0,//总价
    editStatus: false,// true 编辑中
    buttonText: '去结算',
    loadingKd: false,//true 按钮无法提交
    disabledGroup: false,//false 按钮无法提交
    tabCartTotal: '',
  },

  //购物车数据列表
  getCartList(){
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/cart/list',
      data: {
        centreId: _this.data.user.centreId,
        memberId: _this.data.user.id,
        limit: 0,
        offset: 0
      },
      load: 0
    }).then((res)=>{
      let rows = res.data.data.rows;
      if(rows == null) rows = [];//处理后端返回空字符串

      _this.data.good_kd = [];
      _this.data.good_group = [];
      _this.data.checkBoxGoodsKd = [];
      _this.data.checkBoxGoodsGroup = [];
      rows.forEach((item,i)=>{
        if (item.isKuaidi) {
          _this.data.picArr_kd = [];
          if(item.prodlabels.split(",")[i]) _this.data.picArr_kd.push(item.prodlabels.split(",")[i]);
          _this.data.good_kd.push(item);//快递直发
          _this.data.checkBoxGoodsKd.push(item.id);
        }
        else {
          _this.data.picArr_group = [];
          if(item.prodlabels.split(",")[i]) _this.data.picArr_group.push(item.prodlabels.split(",")[i]);
          _this.data.good_group.push(item);//到店自提
          _this.data.checkBoxGoodsGroup.push(item.id);
        }
      })
      _this.setData({
        good_kd: _this.data.good_kd,
        good_group: _this.data.good_group,
        picArr_kd: _this.data.picArr_kd,
        picArr_group: _this.data.picArr_group,
        checkBoxGoodsGroup: _this.data.checkBoxGoodsGroup,
        checkBoxGoodsKd: _this.data.checkBoxGoodsKd,
      })
      _this.reckonTotalPrice(_this.data.good_kd,true,1);
      _this.reckonTotalPrice(_this.data.good_group,true,0);

    })

  },

  //提交
  cartSubmit(event){
    let _this = this;
    let isKuaidi = event.currentTarget.dataset.iskuaidi;
    if(_this.data.editStatus) _this.delCartAll(isKuaidi);//删除
    else  _this.cartSettlement(isKuaidi);//结算
  },

  //去结算
  cartSettlement(isKuaidi){
    let _this = this;
    let items = [];

    if(isKuaidi == 0){
      if(_this.data.checkBoxGoodsGroup.length <= 0) return;
      _this.data.good_group.forEach(item=>{
        if(_this.data.checkBoxGoodsGroup.indexOf(item.id) !== -1) {
          items.push({
            cartId: item.id,
            productId: item.productId,
            total: item.total,
            skuId: item.skuId,
            skuTitle: item.skuTitle,
            marketprice: item.marketprice,
          })
        }
        let order = {cartItems: items}
        wx.setStorageSync('order', JSON.stringify(order));
      })
      wx.navigateTo({
        url: '/pages/index/place-order-entity/place-order-entity'
      })
    } else if(isKuaidi == 1){
      if(_this.data.checkBoxGoodsKd.length <= 0) return;
      _this.data.good_kd.forEach(item=>{
        if(_this.data.checkBoxGoodsKd.indexOf(item.id) !== -1) {
          items.push({
            cartId: item.id,
            productId: item.productId,
            total: item.total,
            skuId: item.skuId,
            skuTitle: item.skuTitle,
            marketprice: item.marketprice,
          })
        }
        let order = {cartItems: items}
        wx.setStorageSync('order', JSON.stringify(order));
      })
      wx.navigateTo({
        url: '/pages/index/place-order-entity/place-order-entity'
      })
    }

  },

  //勾选删除
  delCartAll(isKuaidi){
    let _this = this;
    Dialog.confirm({
      message: '确定删除所选商品吗？',
      cancelButtonText: '再想想',

    }).then(() => {
      //处理id
      let idStr = '';
      let len = 0;//删除的角标总数
      if(isKuaidi == 0){
        _this.data.checkBoxGoodsGroup.filter(item =>{
          idStr += item + ',';
        })
        _this.data.good_group.forEach((goods,index)=>{
          _this.data.checkBoxGoodsGroup.filter(item =>{
            if(goods.id == item)
              len += goods.total;
          })
        })
      } else if(isKuaidi == 1){
        _this.data.checkBoxGoodsKd.filter(item =>{
          idStr += item + ',';
        })
        _this.data.good_kd.forEach((goods,index)=>{
          _this.data.checkBoxGoodsKd.filter(item =>{
            if(goods.id == item)
              len += goods.total;
          })
        })
      }
      idStr = idStr.substr(0,idStr.lastIndexOf(','));

      app.requestUrl({
        method: 'POST',
        url: '/wxapi/cart/delall',
        data: {
          id: idStr,
          memberId: _this.data.user.id,
          centreId: _this.data.user.centreId,
          isKuaidi: isKuaidi
        },
        header: {
          'Content-Type': 'application/json;charset=UTF-8',
          'Authorization': wx.getStorageSync('authToken') || 'empty-token'
        },
      }).then((res)=>{
        app.globalData.cartTotal -= len;
        _this.getCartList();
        _this.setData({
          buttonText: '去结算',
          editStatus: false
        })
      })
    }).catch(()=>{})
  },

  //单条删除
  delGoods(event){
    let _this = this;
    let isKuaidi = event.currentTarget.dataset.iskuaidi;
    let index = event.currentTarget.dataset.index;
    Dialog.confirm({
      message: '确定删除所选商品吗？',
      cancelButtonText: '再想想'
    }).then(() => {
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/cart/del',
        data: {
          itemId: isKuaidi==1 ? _this.data.good_kd[index].id : _this.data.good_group[index].id,
          memberId: _this.data.user.id,
          centreId: _this.data.user.centreId,
          isKuaidi: isKuaidi
        }
      }).then((res)=>{
        if(isKuaidi == 1){//快递直发
          //接口删除 数组也要手动删除
//          _this.data.checkBoxGoodsKd.filter((item)=>{
//            if(item == _this.data.good_kd[index].id)
//              _this.data.checkBoxGoodsKd.splice(index, 1);
//          })
          let filterRes = _this.data.good_kd.filter((item,i) => {
            return i != index
          })
          app.globalData.cartTotal -= _this.data.good_kd[index].total;

          _this.setData({
            good_kd:  filterRes,
            checkBoxGoodsKd:  [],
            isCheckAllKd: false,
          })
          _this.reckonTotalPrice(_this.data.good_kd, null, 1);
        } else if(isKuaidi == 0){//团购
//          接口删除 数组也要手动删除
//          _this.data.checkBoxGoodsGroup.forEach((item, i) =>{
//            if(item === _this.data.good_group[index].id)
//              _this.data.checkBoxGoodsGroup.splice(i, 1);
//          })
          let filterRes = _this.data.good_group.filter((item,i) => {
            return i != index
          })
          app.globalData.cartTotal -= _this.data.good_group[index].total;

          _this.setData({
            good_group:  filterRes,
            checkBoxGoodsGroup:  [],
            isCheckAllGroup: false,
          })
          _this.reckonTotalPrice(_this.data.good_group, null, 0);
        }
      }).catch(()=>{})
    })
  },

  //商品单选 选择
  checkboxChange(event){
    let _this = this;
    let isKuaidi = event.currentTarget.dataset.iskuaidi;//标签使用data-xxxx；xxxx大写会自动转小写
    if (isKuaidi == 0){
      _this.setData({checkBoxGoodsGroup: event.detail})
      _this.reckonTotalPrice(_this.data.good_group,false,0)
      //反全选
      if(_this.data.checkBoxGoodsGroup.length == _this.data.good_group.length)
        _this.setData({isCheckAllGroup: true})

      //去结算按钮是否禁用
      if(_this.data.checkBoxGoodsGroup.length == 0)
      _this.setData({disabledGroup: true})
      else
        _this.setData({disabledGroup: false})
    }
    else if(isKuaidi == 1){
      _this.setData({checkBoxGoodsKd: event.detail})
      _this.reckonTotalPrice(_this.data.good_kd,false,1)
      //反全选
      if(_this.data.checkBoxGoodsKd.length == _this.data.good_kd.length)
        _this.setData({isCheckAllKd: true})

      //去结算按钮是否禁用
      if(_this.data.checkBoxGoodsKd.length == 0)
        _this.setData({loadingKd: true})
      else
        _this.setData({loadingKd: false})
    }

  },

  //全选
  checkboxChangeAll(event){
    let _this = this;
    let isKuaidi = event.currentTarget.dataset.iskuaidi;//标签使用data-xxxx；xxxx大写会自动转小写
    if (isKuaidi == 0) {//到店自提
      _this.data.isCheckAllGroup = !_this.data.isCheckAllGroup;//控制全选是否选中，true选中
      if(_this.data.isCheckAllGroup){
        _this.data.good_group.forEach((item)=>{
          _this.data.checkBoxGoodsGroup.push(item.id);
        })
        _this.data.disabledGroup = false;
      } else {
        _this.data.checkBoxGoodsGroup = [];
        _this.data.disabledGroup = true;
      }
      _this.reckonTotalPrice(_this.data.good_group,_this.data.isCheckAllGroup,0);
      _this.setData({
        checkBoxGoodsGroup: _this.data.checkBoxGoodsGroup,
        isCheckAllGroup: _this.data.isCheckAllGroup,
        disabledGroup: _this.data.disabledGroup,
      })
    } else if(isKuaidi == 1){//快递直发
      _this.data.isCheckAllKd = !_this.data.isCheckAllKd;//控制全选是否选中，true选中
      if(_this.data.isCheckAllKd){
        _this.data.good_kd.forEach((item)=>{
          _this.data.checkBoxGoodsKd.push(item.id);
        })
        _this.data.loadingKd = false;
      } else {
        _this.data.checkBoxGoodsKd = [];
        _this.data.loadingKd = true;
      }
      _this.reckonTotalPrice(_this.data.good_kd,_this.data.isCheckAllKd,1);
      _this.setData({
        checkBoxGoodsKd: _this.data.checkBoxGoodsKd,
        isCheckAllKd: _this.data.isCheckAllKd,
        loadingKd: _this.data.loadingKd,
      })
    }
  },

  //总计
  reckonTotalPrice(i,isTrue,isKuaidi){
    //van-submit-bar标签，price属性（单位分）
    let _this = this;
    if(isKuaidi == 0){
      let rec = i.reduce((total, item) =>
        total + (_this.data.checkBoxGoodsGroup.indexOf(item.id) !== -1 ? item.marketprice * item.total * 100 : 0),0);
      _this.setData({
        groupTotalPrice: rec,
        isCheckAllGroup: isTrue==null ? _this.data.isCheckAllGroup : isTrue
      })
    } else if(isKuaidi == 1){
      let rec = i.reduce((total, item) =>
        total + (_this.data.checkBoxGoodsKd.indexOf(item.id) !== -1 ? item.marketprice * item.total * 100 : 0),0);
      _this.setData({
        kdTotalPrice: rec,
        isCheckAllKd: isTrue==null ? _this.data.isCheckAllKd : isTrue
      })
    }
  },

  //改变购物车数量
  totalChange (event) {
    let goods = event.currentTarget.dataset.goods;
    let index = event.currentTarget.dataset.index;  // 获取数据的索引
    let iskuaidi = event.currentTarget.dataset.iskuaidi;  // 获取数据的索引

    let total = ''
    if(event.type=='blur') {
      total = event.detail.value;

      let tempTotal = 0;//本次改变的数值
      if(total > goods.total){//加
        tempTotal = total - goods.total;
        app.globalData.cartTotal += tempTotal;
      } else {//减
        tempTotal = goods.total - total;
        app.globalData.cartTotal -= tempTotal;
      }
    }
    else if(event.type=='minus') {
      total = goods.total - 1;
      app.globalData.cartTotal -= 1;
    }
    else if(event.type=='plus') {
      total = goods.total + 1;
      app.globalData.cartTotal += 1;
    }

    let currentTarget = {currentTarget: {dataset: {goods: goods, total: total, index: index, iskuaidi: iskuaidi,}}}
    this.changeCart(currentTarget)
  },

  //改变购物车数量接口
  changeCart (event) {
    let _this = this;
    let goods = event.currentTarget.dataset.goods;
    let isKuaidi = event.currentTarget.dataset.iskuaidi;
    let total = event.currentTarget.dataset.total;
    let index = event.currentTarget.dataset.index;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/cart/edit',
      data: {
        mid: _this.data.user.id,
        centreId: _this.data.user.centreId,
        id: goods.id,
        total: total,
        isKuaidi: isKuaidi
      }
    }).then((res) => {
      let temp_kd = 'good_kd[' + index + '].total';
      let temp_group = 'good_group[' + index + '].total';
      if(isKuaidi == 1){
        _this.setData({
          [temp_kd]: total
        })
        _this.reckonTotalPrice(_this.data.good_kd, null, 1);
      } else if(isKuaidi == 0) {
        _this.setData({
          [temp_group]: total
        })
        _this.reckonTotalPrice(_this.data.good_group, null, 0);
      };
      console.log(wx.getStorageSync('cartTotal'));
      _this.setData({
        tabCartTotal: wx.getStorageSync('cartTotal'),
      })
    })
  },


  //编辑
  editClick(event){
    let _this = this;
    let isKuaidi = event.currentTarget.dataset.iskuaidi;
    _this.setData({
      editStatus: !_this.data.editStatus,
    })
    _this.setData({
      buttonText: _this.data.editStatus ? '删除' : '去结算',
    })
  },

  //tab切换
  cartChange(event){
    let _this = this;
    _this.setData({
      cartActive: event.detail.index
    })
  },

  //商品详情
  toGoodItem(event){
    wx.navigateTo({
      url: '/subIndex/index/good-item/good-item?productId=' + event.currentTarget.dataset.productid
    })
  },

  //监听app全局变量变化回调
  watchBack: function (value){
    this.setData({
      tabCartTotal: value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      user: app.getUser(),
      tabCartTotal: wx.getStorageSync('cartTotal'),
    })
    wx.removeStorageSync('order')//删除订单缓存

    this.getCartList();

    app.watch(this.watchBack);//监听app全局变量
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})